﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Ys.Base.Common
{
    /// <summary>
    /// 常用的Tools应用功能
    /// </summary>
    public class YsTools
    {
        /// <summary>
        /// 创建一个编号 如订单编号
        /// </summary>
        /// <param name="NoHead">头部</param>
        /// <param name="type">0长拼接 1 端拼接</param>
        /// <param name="random"></param>
        /// <returns></returns>
        public static string GetNewNo(string NoHead = null, int type = 0, Random random = null)
        {
            var No = new StringBuilder();
            if (type == 0)
            {
                No.Append(NoHead);
                No.Append(DateTime.Now.ToString("yyMMddHHmmss"));
                No.Append(GetRandom(3, random: random));
            }
            else if (type == 1)
            {
                No.Append(NoHead);
                No.Append(DateTime.Now.ToString("yyMMdd"));
                No.Append(GetRandom(4, random: random));
            }
            return No.ToString();
        }

        /// <summary>
        /// 获取一个随机数
        /// </summary>
        /// <param name="digit">随机数的位数</param>
        /// <param name="RandomArray">随机数组</param>
        /// <returns></returns>
        public static string GetRandom(int digit = 1, string[] RandomArray = null, Random random = null)
        {
            var slist = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            slist = RandomArray == null ? slist : RandomArray;
            var No = new StringBuilder();
            Random r = new Random();
            if (random != null)
            {
                r = random;
            }
            for (int i = 0; i < digit; i++)
            {
                No.Append(slist[r.Next(0, slist.Length)]);
            }
            return No.ToString();
        }
        /// <summary>
        /// 将对象转换json
        /// </summary>
        /// <param name="Obj">要转的对象</param>
        /// <param name="IsSmallHump">是否小驼峰</param>
        /// <returns></returns>
        public static string ToJson(object? Obj,bool IsSmallHump=false)
        {
            
            var json = string.Empty;
            if (Obj == null)
                return json;
            try {
                if (Obj.GetType() == typeof(string) || Obj.GetType() == typeof(String))
                { return json; }
                if (IsSmallHump)
                {
                    var setting = new JsonSerializerSettings
                    {
                        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                    };

                    json = JsonConvert.SerializeObject(Obj,setting);
                }else
                json = JsonConvert.SerializeObject(Obj);
            }
            catch { }
            return json;
        }

        /// <summary>
        /// 将Jason反序列化未数据对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(string json)
        {
            return (T)JsonConvert.DeserializeObject(json, typeof(T));
        }



        /// <summary>
        /// 对Model快速更新到目标对象 只更新非初始化值对象 自动跳过Model基础数值 "Id", "Guid", "Status", "CreateTimeStamp", "UpTimeStamp", "CreateTime" 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Value">更新来源对象</param>
        /// <param name="ToValue">要更新的目标对象</param>
        /// <param name="FileList">要跳过更新属性字段默认跳过"Id", "Guid", "Status", "CreateTimeStamp", "UpTimeStamp", "CreateTime"</param>
        /// <returns></returns>
        public static T UpModel<T>(T Value, T ToValue, List<string> FileList = null)
        {
            if (FileList == null)
            {
                FileList = new List<string>();
            }
            FileList.AddRange(new List<string> { "Id", "Guid", "Status", "CreateTimeStamp", "UpTimeStamp", "CreateTime" });
            return UpObject(Value, ToValue, FileList);
        }


        /// <summary>
        /// 将来源数据快速更新到目标对象 只更新非Null对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Value">更新来源对象</param>
        /// <param name="ToValue">要更新的目标对象</param>
        /// <param name="FilteList">要跳过更新属性</param>
        /// <returns></returns>
        public static T UpObject<T>(T Value, T ToValue, List<string> FilteList = null)
        {
            T Rv = ToValue;
            try
            {
                if (FilteList == null)
                {
                    FilteList = new List<string>();
                }

                if (Value.GetType() != ToValue.GetType())
                {
                    return ToValue;
                }

                Type type = ToValue.GetType();

                var NewT = Activator.CreateInstance(type);

                PropertyInfo[] PropertyList = type.GetProperties();
                foreach (PropertyInfo item in PropertyList)
                {
                    var rname = FilteList.Find(o => o.ToLower() == item.Name.ToLower());
                    if (rname == null)
                    {
                        var getv = item.GetValue(Value);
                        var tov = item.GetValue(ToValue);
                        var defaultvalue = item.GetValue(NewT);

                        if (getv != null)
                        {
                            if (!getv.Equals(defaultvalue) && getv != tov)
                            {
                                item.SetValue(Rv, getv);
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                var message = ex.Message;
                Rv = ToValue;
            }

            return Rv;
        }

        /// <summary>
        /// 测试服务器计算性能
        /// </summary>
        /// <param name="N">斐波那契数计算次数默认40</param>
        /// <returns></returns>
        public static object GetServerRunPer(int N = 40)
        {
            Stopwatch time = new Stopwatch();
            time.Start();
            Console.WriteLine("计算结果：" + Fib(N));
            time.Stop();

            var t = time.Elapsed.TotalMilliseconds / 1000;

            return "计算" + N + "个斐波那契数列和耗时:" + t + "秒";
        }

        /// <summary>
        /// 斐波那契数列和
        /// </summary>
        /// <param name="n">次数</param>
        /// <returns></returns>
        public static int Fib(int n)
        {
            if (n < 2)
                return n;
            else
                return Fib(n - 2) + Fib(n - 1);
        }


        /// <summary>
        /// 自动对比数据对象进行更新 默认自动跳过 "Id", "AddTime", "Gid"   如果指定 Notcolumn 则使用指定跳过
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Dto">要更新的目标对象</param>
        /// <param name="UpDto">更新的值</param>
        /// <param name="UpColumn">指定更新字段</param>
        /// <param name="Notcolumn">指定的跳过过滤字段</param>
        /// <returns></returns>
        public static T AutoUpObjectData<T>(ref T Dto, T UpDto, List<string> UpColumn = null, List<string> Notcolumn = null) where T : class, new()
        {
            //跳过的字段
            var _notcolumn = new List<string> { "Id", "AddTime", "Gid" };
            if (Notcolumn == null || Notcolumn.Count == 0)
            {
                Notcolumn = _notcolumn;
            }
            else
            {
                Notcolumn.AddRange(_notcolumn);
            }
            if (UpColumn == null || UpColumn.Count == 0)
            {
                UpColumn = new List<string>();

                foreach (var item in typeof(T).GetProperties())
                {
                    UpColumn.Add(item.Name);
                }
            }

            for (int i = 0; i < UpColumn.Count; i++)
            {
                UpColumn[i] = UpColumn[i].ToLower();
            }

            for (int i = 0; i < Notcolumn.Count; i++)
            {
                Notcolumn[i] = Notcolumn[i].ToLower();
            }


            //进行反射循环对比是否需要修改新的值后更新
            var collist = new List<PropertyInfo>();
            // collist = typeof(T).GetProperties().Where(w => UpColumn.Contains(w.Name) && !Notcolumn.Contains(w.Name)).ToList();
            var typeclist = typeof(T).GetProperties().ToList();
            foreach (var col in typeclist)
            {
                if (UpColumn.IndexOf(col.Name.ToLower()) >= 0 && Notcolumn.IndexOf(col.Name.ToLower()) < 0)
                {
                    collist.Add(col);
                }
            }
            var initData = new T();
            var ilist = initData.GetType().GetMembers();
            if (initData.GetType().GetMethod("Init") != null)
            {
                initData.GetType().GetMethod("Init").Invoke(initData, new object[] { });
            }
            foreach (var item in collist)
            {//空值和等于创建初始化的将被忽律

                var valuedata = item.GetValue(Dto);
                var valueup = item.GetValue(UpDto);
                var init = item.GetValue(initData);
                //针对status特特殊处理
                if (item.Name.ToLower() == "status")
                { init = 0; }

                if (valueup != null && (!valueup.Equals(valuedata) && (!valueup.Equals(init))))
                {
                    if (valueup.ToString().IsNotNull())
                    {
                        if (valueup.ToString() == "[null]")
                            item.SetValue(Dto, null);
                        else
                            item.SetValue(Dto, valueup);
                    }
                }
            }

            return Dto;
        }



    }
}
